/**
 * 此组件，适用于安全问题原因和质量问题原因
 */
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import App from 'layout/App.js'
import './index.less';
import { FormControl, Button, Row, Col, Icon, Modal, Select, Upload} from 'tinper-bee';
import { searchWorkProList, editWorkPro, deleteWorkPro, addWorkPro } from './workproblemreason.config.js'
import { vendorsDanger as danger, vendorsSuccess as success } from 'utils/config.js';
import CommonModal from './../../components/CommonModal/index.jsx';
import AddTreeNode from './AddTreeNode.jsx';
import RenderTreeTitle from './RenderTreeTitle.jsx';
import PresetTemplate from './../../components/PresetTemplate/index.jsx';
import 'nprogress/nprogress.css';
import NProgress from 'nprogress';
import Tree from 'bee-tree';
import  "bee-tree/build/Tree.css";
import Switch from 'bee-switch';
import 'bee-switch/build/Switch.css';
const TreeNode = Tree.TreeNode;
const Option = Select.Option;
export default class WorkProblemReason extends Component {
	constructor(props) {
		super(props);
		this.state = {
			treeData: [],
			isHover: "",
			editKey: "",
			isHaveTreeDataStatus: false,
			isAddTreeNodeStatus: false,
			item: null,
			expendKey: [],
			chooseActiveStatus: 0,
			showModal: false,
			deleteItem: null,
			searchText: '',
			modal: false,
			callbackItem: {},
			searchAllItem: 0,
			btnColor: '',
			allStopFlag: true,
			isPos: [],
			showDisabled: false,
		};

	}
	init = () => {
		let _me = this;
		let category = this.distinguishPage('request');

		searchWorkProList({'isAjax': 1, 'ieStamp': new Date().getTime(), status: this.state.showDisabled ? 2 : 1 , category: category})
		.then(function(res){
			if (res.data.resultCode != 'busi_ex') {
				if(res.data.result.length !== 0){
					let data = res.data.result;
					// 加工后台数据添加 name, key, id 组件组件需要属性
					_me.loopNextData(data);
					_me.setState({
						treeData: res.data.result,
						isHaveTreeDataStatus: true
					});
				}else{
					_me.setState({
						treeData: [],
						isHaveTreeDataStatus: false
					});
				}
			} else {
				danger({'text': res.data.exMsg})
			}
		})
	}
	loopNextData = (data) => {
		let _me = this;
		data.forEach(function(item, index){
			item['name'] = item.sname;
			item['key'] = item.scode;
			item['id'] = item.pkReason;
			item['className'] = false;
			if(item.childReason){
				_me.loopNextData(item.childReason)
			}
		})
	}
	handlerAddTreeNode = () => {
		if(!this.state.modal){
			this.setState({
				isAddTreeNodeStatus: true,
				isHaveTreeDataStatus: true,
				modal: true
			});
		}
	}
	handlerCloseAddTreeNode = (level, flag) => {
		if(!this.state.treeData.length){
			this.setState({
				isAddTreeNodeStatus: false,
				isHaveTreeDataStatus: false,
				modal: flag
			});
		} else {
			this.setState({
				isAddTreeNodeStatus: false,
				isHaveTreeDataStatus: true,
				modal: flag
			});
		}
	}
	handlerAdd = (payload, level, item, callback) => {
		if(payload.name === '' || payload.code === ''){
			danger({'text': '问题原因信息填写不完整！'});
			return;
		}
		/// 校验是否符合标准
		let codeReg=/^[a-zA-Z0-9_-]+$/i;
		if (payload.name.length > 50) {
			//danger({'text': '信息请限制在50个字符！'});
			//return;
			if (codeReg.test(payload.code)) {
				if(payload.code.length > 20){
					danger({'text': '编码超过了20个字符，请精简！'});
					return;
				}
			} else {
				if(payload.code.length > 20){
					danger({'text': '长度错误：编码超过了20个字符，请精简！, 内容错误：只支持英文、数字、中下划线'});
					return;
				} else {
					danger({'text': '内容错误：只支持英文、数字、中下划线'});
					return;
				}
			}
		} else {
			if (codeReg.test(payload.code)) {
				if(payload.code.length > 20){
					danger({'text': '编码超过了20个字符，请精简！'});
					return;
				}
			} else {
				if(payload.code.length > 20){
					danger({'text': '长度错误：编码超过了20个字符，请精简！, 内容错误：只支持英文、数字、中下划线'});
					return;
				} else {
					danger({'text': '内容错误：只支持英文、数字、中下划线'});
					return;
				}
			}
		}

		let _me = this;
		let category = _me.distinguishPage("request");
		let param = {'enableStatus':1,'sname': payload.name.trim(), 'scode': payload.code, 'isAjax': 1, category : category};
		// 如果为同级添加则pkParent为父级pkParent
		if(item !== undefined && item !== null) {
			let timedPkParent = payload.isSameLevel ? {'pkParent': item.pkParent} : {'pkParent': item.pkReason};
			param = Object.assign({}, param, timedPkParent);
		}
		addWorkPro(param).
		then(function(res){
			if(res.data.resultCode !== 'busi_ex'){
				_me.init();
				_me.setState({
					isHaveTreeDataStatus: true
				});
				callback && callback();
			}else{
				danger({'text': res.data.exMsg});
			}
		})
	}
	onMouseEnter = (node) => {
		let _me = this;
		if(!_me.state.modal){
			if(_me.state.isHover === node.node.props.title.props.item.key){
				_me.loopNextClearClassNameData(this.state.treeData);
				_me.setState({
					isHover: '',
					isPos: node.node.props.pos.split('-'),
					callbackItem: {},
					treeData: this.state.treeData
				})
			} else {
				_me.loopNextClearClassNameData(this.state.treeData);
				_me.setState({
					isHover: node.node.props.title.props.item.key,
					isPos: node.node.props.pos.split('-'),
					callbackItem: {},
					treeData: this.state.treeData
				})
			}
		}
	}
	loopNextClearClassNameData = (data) => {
		let _me = this;
		data.forEach(function(item, index){
			item['className'] = false;
			if(item.childReason){
				_me.loopNextData(item.childReason)
			}
		})
	}
	handlerEditCancel = (flag) => {
		this.setState({
			isHover: "",
			editKey: "",
			modal: flag
		})
	}
	handlerEditConfirm = (item, flag) => {
		let _me = this;
		let nameReg=/^\S+$/i;
		if(item.name.length===0){
			danger({'text': '请输入具体内容！'});
			return;
		} else {
			if (item.name.length > 50) {
				danger({'text': '请限制在50个字符之内！'});
				return;
			}
		}
		//_me.setState({
		//	callbackItem: item
		//});
		let param ={
			'scode': item.scode,
			'sname': item.name.trim(),
			'pkReason': item.pkReason,
			'changeFlag': item.changeFlag,
			'isAjax': 1
		};
		editWorkPro(param).
		then(function(res){
			if(res.data.resultCode !== 'busi_ex'){
				_me.init();
				// let data = res.data.result;
				// data['name'] = data.sname;
				// data['key'] = data.scode;
				// data['id'] = item.pkReason;
				// _me.loopNextEdit(_me.state.treeData, item, data);
				_me.setState({
					isHover: "",
					editKey: "",
					modal: flag,
					// treeData: _me.state.treeData,
					callbackItem: item
				})
			}else{
				danger({'text': res.data.exMsg})
			}
		})
	}
	loopNextEdit = (data, propsItem, dataItem) => {
		let _me = this;
		data.forEach(function(item, index){
			if(item.key === propsItem.key) {
				data.splice(index, 1, Object.assign({}, dataItem, {'childReason': propsItem.childReason}));
			} else {
				if(item.childReason){
					_me.loopNextEdit(item.childReason, propsItem, dataItem);
				}
			}
		})
	}
	onExpand = (item, list) => {
		let itemIndex = this.state.expendKey.indexOf(list.node.props.title.props.item.key);
		let save = [];
		let saveBox = [];
		let saveItem = {};
		this.state.treeData.forEach(function(item, index){
		if(item.key == list.node.props.title.props.item.key){
				save.push(item.key);
				saveItem = item;
				if(item.childReason){
					item.childReason.forEach(function(item, index){
						save.push(item.key)
					})
				}
			}
		})
		if(itemIndex == -1 && list.expanded != false){
			this.setState({
				expendKey: [list.node.props.title.props.item.key, ...this.state.expendKey]
			});
		} else {
			if (saveItem.childReason) {
				saveBox = this.state.expendKey.filter(function(item){
					return save.indexOf(item) == -1
				})
				this.setState({
					expendKey: saveBox
				});
			} else {
				this.state.expendKey.splice(itemIndex, 1);
				this.setState({
					expendKey: this.state.expendKey
				});
			}
		}
	}
	handlerEditRender = (item, flag) => {
		this.setState({
			editKey: item.key,
			modal: flag
		});
	}
	handlerCreateRender = (item, flag) => {
		this.state.expendKey.push(item.key)
		this.setState({
			item: item,
			expendKey: this.state.expendKey,
			modal: flag
		});
	}
	//添加同级
	handleCreateSameLevel = (item, flag) => {
		this.state.expendKey.push(item.key)
		this.setState({
			item: item,
			expendKey: this.state.expendKey,
			modal: flag
		});
	}
	handlerDeleteRender = (item) => {
		let _me = this;
		if(item.childReason){
			if(item.childReason.length !== 0){
				danger({'text': '此条问题原因为父级不能删除'});
				return ;
			} else {
				_me.setState({
					showModal: true,
					deleteItem: item
				});
			}
		} else {
			_me.setState({
				showModal: true,
				deleteItem: item
			});
		}
	}
	handlerDelete = (item) => {
		let _me = this;
		_me.setState({
			deleteItem: item
		});
		deleteWorkPro({'pkReason': item.pkReason, 'changeFlag': item.changeFlag, 'isAjax': 1}).
			then(function(res){
				if(res.data.resultCode !== 'busi_ex'){
					_me.loopNext(_me.state.treeData);
					_me.loopNextDeleteEmptyChildren(_me.state.treeData);
					if(_me.state.treeData.length === 0){
						_me.setState({
							treeData: _me.state.treeData,
							isHaveTreeDataStatus: false
						});
					} else {
						_me.setState({
							treeData: _me.state.treeData
						});
					}
					success({'text': '删除成功！'});
				} else {
					danger({'text': res.data.exMsg});
				}
			})
		_me.setState({
			showModal: false
		});
	}
	loopNext = (data) => {
		let _me = this;
		data.forEach(function(item, index){
			if(item.key === _me.state.deleteItem.key) {
				data.splice(index, 1);
			} else {
				if(item.childReason){
					_me.loopNext(item.childReason)
				}
			}
		})
	}
	loopNextDeleteEmptyChildren = (data) => {
		let _me = this;
		data.forEach(function(item, index){
			if(item.childReason) {
				if(item.childReason.length === 0){
					delete item.childReason
				} else {
					_me.loopNextDeleteEmptyChildren(item.childReason);
				}
			}
		})
	}
	componentDidMount = () => {
		this.init();
		window.addEventListener('scroll', this.handlerScrollWindow);
		document.addEventListener('click', () => {
			this.setState({
				isHover: '',
				isPos: []
			});
        });
	}
	chooseAll = (e) => {
		e.nativeEvent.stopImmediatePropagation();
	}
	handlerExpanded = (e, data) => {
		if(this.state.modal) return;
		let newExpendKey = [];
		let type = this.state.searchAllItem || e.target.getAttribute('data-index');
		if (type == 2){
			this.state.treeData.forEach(function(item, index){
				newExpendKey.push(item.key);
			})
		} else if (type == 3){
			this.state.treeData.forEach(function(item, index){
				newExpendKey.push(item.key);
				if(item.childReason){
					item.childReason.forEach(function(item, index){
						newExpendKey.push(item.key);
					})
				}
			})
		}
		this.setState({
			expendKey: newExpendKey,
			chooseActiveStatus: type,
			searchAllItem: 0
		});
	}
	close = () => {
		this.setState({
			showModal: false
		});
	}
	handlerSearchValue = (e) => {
		this.setState({
			searchText: e.target.value.trim()
		});
	}
	handlerSearch = () => {
		let _me = this;
		let data = this.state.treeData;
		let spaceReg=/\s+/i;
		let keyWord = this.state.searchText;
		if(this.state.modal) return;
		if(this.state.searchText === ''){
			danger({'text': '请输入具体内容！'});
			return;
		}
		if(spaceReg.test(this.state.searchText)){
			keyWord = this.state.searchText.split(/\s+/);
		} else {
			keyWord = this.state.searchText;
		}
		this.loopNextSearchData(data, keyWord);
		this.setState({
			treeData: data,
			searchAllItem: 3
		}, function(){
			_me.handlerExpanded()
		});
	}
	loopNextSearchData = (data, keyword) => {
		let _me = this;
		if(typeof(keyword) == 'string'){
			data.forEach(function(item, index){
				if(item.sname.indexOf(keyword) > -1 || item.scode.indexOf(keyword) > -1){
					item['className'] = true;
				} else {
					item['className'] = false;
				}
				if(item.childReason){
					_me.loopNextSearchData(item.childReason, keyword)
				}
			})
		} else {
			data.forEach(function(item, index){
				var parentItem = item;
				var controlSme = true;
				keyword.forEach(function(item){
					if(parentItem.sname.indexOf(item) > -1 || parentItem.scode.indexOf(item) > -1){
						if(controlSme){
							parentItem['className'] = true;
						}
					} else {
						parentItem['className'] = false;
						controlSme = false;
					}
				})
				if(parentItem.childReason){
					_me.loopNextSearchData(parentItem.childReason, keyword)
				}
		})
		}
	}
    changeBtnColorToNone = () => {
    	this.setState({
    		btnColor: 'primary'
    	});
    }
    changeBtnColorToParamry = () => {
    	this.setState({
    		btnColor: ''
    	});
    }
    handlerScrollWindow = (e) => {
	    if (e.target.scrollingElement.scrollTop >= 10) {
	      this.refs.fixedTop.className = 'header clearfix tofixed';
	      this.refs.contenBox.className = 'content marginTop-50';
	    } else {
	      this.refs.fixedTop.className = 'header clearfix';
	      this.refs.contenBox.className = 'content';
	    }
	}
	hideModal = () => {
		this.setState({
			showModal: false
		});
	}
	handleClearInput = () => {
		let _me = this;
        _me.setState({
            searchText: ''
        });
	}
	onShowDisabledChange = () => {
		this.setState({
			showDisabled: !this.state.showDisabled
		},()=>{
			this.init();
		});
	}

	distinguishPage = (from) => {
		let pathname = location.pathname;
		let filename = pathname.split("/")[1].split(".")[0];
		let res = '';
		switch (from){
			case "title" :
				let title ='';
				switch(filename){
					case "workproblemreason" :
						title = '质量问题原因'
						break;
					case "securityproblemreason":
						title = '安全问题原因'
						break;
					default:
						title = '问题原因'
						break;
				}

				res = title;
			break;
			case "request":
				let category ='';
				switch(filename){
					case "workproblemreason" :
						category = 0
						break;
					case "securityproblemreason":
						category = 1
						break;
				}

				res = category;
			break;
		}
		return res
	}

	render(){
	console.log(this.state.treeData)
		let _me = this;
		const loop = data => data.map((item) => {
			if (item.childReason && item.childReason !== null) {
				return <TreeNode title={<RenderTreeTitle item={item}
														 editKey={_me.state.editKey}
													     isHover={_me.state.isHover}
													     isPos={this.state.isPos}
													     onCloseAddTreeNode={this.handlerCloseAddTreeNode}
													     onAdd={this.handlerAdd}
													     callbackItem={this.state.callbackItem}
													     onEditRender={this.handlerEditRender}
														 onCreateRender={this.handlerCreateRender}
														 onCreateSameLevel={this.handleCreateSameLevel}
													     onDeleteRender={this.handlerDelete}
													     onEditCancel={this.handlerEditCancel}
														 onEditConfirm={this.handlerEditConfirm}
														 onEnableStatusChanged={this.init}
													     className={item.className}></RenderTreeTitle>} key={item.key}>{loop(item.childReason)}</TreeNode>;
			}
			return <TreeNode title={<RenderTreeTitle item={item}
												 editKey={_me.state.editKey}
												 isHover={_me.state.isHover}
												 isPos={this.state.isPos}
												 onCloseAddTreeNode={this.handlerCloseAddTreeNode}
												 onAdd={this.handlerAdd}
												 callbackItem={this.state.callbackItem}
												 onEditRender={this.handlerEditRender}
												 onCreateRender={this.handlerCreateRender}
												 onCreateSameLevel={this.handleCreateSameLevel}
												 onDeleteRender={this.handlerDelete}
												 onEditCancel={this.handlerEditCancel}
												 onEditConfirm={this.handlerEditConfirm}
												 onEnableStatusChanged={this.init}
											     className={item.className}></RenderTreeTitle>} key={item.key} isLeaf={item.isLeaf} />;
		});
		const treeNodes = loop(this.state.treeData);
		let category = this.distinguishPage('request')
		const uploadConfig = {
			name: 'file',
			action: '/problemReason/importFromExcel',
			showUploadList: false,
			headers: {},
			data:{ category },
			onChange(info) {
			  if (info.file.status !== 'uploading') {
				// console.log(info.file, info.fileList);
			  }
			  if (info.file.status === 'done') {
				if (info.file.response.resultCode === 'ok') {
					_me.init();
					success({'text': '导入成功！'});
				} else {
					danger({'text': `${info.file.response.exMsg}！`});
				}
			  } else if (info.file.status === 'error') {
				danger({'text': `${info.file.response.exMsg}！`});
			  }
			},
		};
		return(
			<App onscroll={this.handlerScrollWindow}>
	            <CommonModal show={this.state.showModal}
	                         cancel={this.close}
	                         confirm={this.handlerDelete}
	                         content={''}
	                         backdrop={false}
	                         hide={this.hideModal}></CommonModal>
				<div className="product_container">
					<div className="header clearfix" ref="fixedTop">
						<h1 className="fl">{this.distinguishPage("title")}</h1>
						<div className="search clearfix fl">
							<label className="search_label">搜索 :</label>
							<FormControl className="fl search_input_format"
								placeholder="请输入问题原因编码、名称"
								onChange={this.handlerSearchValue}
								onFocus={ this.changeBtnColorToNone }
								value={this.state.searchText}
								onBlur={ this.changeBtnColorToParamry }/>
							<span className="clear-input-content" onClick={this.handleClearInput}>x</span>
							<Button 
								colors={this.state.btnColor} 
								className="fl btn_style_format" 
								onClick={this.handlerSearch}>
								<Icon type="uf-search-light-2"></Icon>
							</Button>
						</div>
						<Button colors="primary" className="fr btn" onClick={this.handlerAddTreeNode}>创建一级问题原因</Button>
						<Select
							defaultValue="问题原因模板"
							style={{ width: 140, float: 'right', textAlign: 'center' }}
							dropdownMatchSelectWidth={true}
							showSearch={true}
							allowClear={false}
						>
							<Option value="downloadTemplate" key="downloadTemplate">
								<a className="download-a-target" href="https://gysy-pmc-pub.oss-cn-beijing.aliyuncs.com/files/%E5%AE%89%E5%85%A8%E9%97%AE%E9%A2%98%E5%8E%9F%E5%9B%A0%E6%A8%A1%E6%9D%BF.xlsx">下载导入模板</a>
							</Option>
							<Option value="importTemplate" key="importTemplate">
								<Upload {...uploadConfig}>
									导入数据
								</Upload>
							</Option>
						</Select>
					</div>
					<div className="content" ref="contenBox">
						<div className="choose-showLevel clearfix">
							
							{ this.state.isHaveTreeDataStatus && <div >
								<span className="fl choose-showLevel-title">展示：</span>
								<div className="choose-btn fl">
									<span data-index="1" onClick={this.handlerExpanded} className={this.state.chooseActiveStatus == 1? 'active': ''}>一级</span>
									<span data-index="2" onClick={this.handlerExpanded} className={this.state.chooseActiveStatus == 2? 'active': ''}>二级</span>
									<span data-index="3" onClick={this.handlerExpanded} className={this.state.chooseActiveStatus == 3? 'active': ''}>三级</span>
								</div>
							</div>}
									{/* <p className="fl">注：鼠标滑过问题原因名称，显示 <span>操作按钮</span>，另外目录只支持创建<span>3级</span>.</p> */}
									<div className="fr">
										<Switch
											checked={this.state.showDisabled}
											onChange={this.onShowDisabledChange}
											// className=""
											size = 'sm'
										/>
										<span className = 'showdisabletext'>显示停用</span>
									</div>
									
								</div>
						{!this.state.isHaveTreeDataStatus && <p className="notice-text"><span>暂无可用</span>的问题原因档案， 请点击右上角 创建一级问题原因 按钮, 开始创建 !</p>}
						
						{this.state.isHaveTreeDataStatus && <div style={{'width': '100%'}} onClick={this.chooseAll}><Tree onMouseLeave={this.onMouseLeave}
																  onMouseEnter={this.onMouseEnter}
																  openIcon={<Icon type="uf-minus" />}
																  closeIcon={<Icon type="uf-plus"/>}
																  expandedKeys={this.state.expendKey}
																  onExpand={this.onExpand}
																  >
							{treeNodes}
		      			</Tree></div>}
		      			{this.state.isAddTreeNodeStatus && <AddTreeNode onClose={this.handlerCloseAddTreeNode}
		      															onAdd={this.handlerAdd}
		      															level={''}
		      															></AddTreeNode>}
					</div>
				</div>
			</App>)
	}
}
